<template>
  <div class="login-bg" :style="{ backgroundImage: `url(${illustrationUrl})` }">
    <div class="login-main">
      <!-- 左侧宣传区 -->
      <div class="login-side">
        <div class="brand-logo">
          <img :src="logoUrl" alt="LOGO" />
          <span class="brand-title">梓桐健康医药网</span>
        </div>
        <div class="slogan">
          <h2>定制健康服务，守护您的用药安全</h2>
          <p>专业药师在线，正品保障，健康生活每一天</p>
        </div>
      </div>
      <!-- 右侧注册卡片 -->
      <div class="login-form-card">
        <h2 class="form-title">用户注册</h2>
        <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名" clearable size="large">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" clearable size="large">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" clearable size="large">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号码" clearable size="large">
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" clearable size="large">
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleRegister" :loading="loading" class="submit-btn" size="large" style="width:100%">
            注册
          </el-button>
        </el-form-item>
          <el-form-item class="form-links">
          <el-link type="primary" @click="$router.push('/login')">已有账号？立即登录</el-link>
        </el-form-item>
      </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { User, Lock, Phone, Message } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'
import logoUrl from '@/assets/logo.png'
import illustrationUrl from '@/assets/login-illustration.png'

const router = useRouter()
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})
const loading = ref(false)
const registerFormRef = ref(null)

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
    if (registerForm.value.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
const rules = {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    // 获取所有用户以生成新ID
    const usersResponse = await axios.get('http://localhost:3000/users')
    const users = usersResponse.data
    
    // 找到当前最大的ID
    const maxId = users.reduce((max, user) => {
      const userId = parseInt(user.id)
      return isNaN(userId) ? max : Math.max(max, userId)
    }, 0)
    
    const userData = {
      id: (maxId + 1).toString(),
      username: registerForm.value.username,
      password: registerForm.value.password,
      phone: registerForm.value.phone,
      email: registerForm.value.email,
      role: 'user',
      status: 'active',
      createTime: new Date().toISOString(),
      favorites: [],
      avatar: 'https://example.com/placeholder-avatar.jpg'
    }
    
    await axios.post('http://localhost:3000/users', userData)
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: linear-gradient(120deg, #e6f0fa 0%, #fafdff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.login-main {
  width: 900px;
  min-height: 520px;
  background: rgba(255,255,255,0.95);
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.10);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
.login-side {
  flex: 1.2;
  background: none;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 36px 48px 48px;
  min-width: 0;
}
.brand-logo {
  display: flex;
  align-items: center;
  margin-bottom: 32px;
}
.brand-logo img {
  height: 40px;
  margin-right: 12px;
}
.brand-title {
  font-size: 22px;
  font-weight: bold;
  color: #e4393c;
  letter-spacing: 2px;
}
.slogan h2 {
  font-size: 24px;
  color: #222;
  margin-bottom: 12px;
  font-weight: 600;
}
.slogan p {
  color: #666;
  font-size: 15px;
  margin-bottom: 24px;
}
.login-form-card {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding: 48px 36px 36px 36px;
  min-width: 340px;
  max-width: 380px;
  margin: 0 32px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.form-title {
  text-align: center;
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 32px;
  color: #222;
}
.submit-btn {
  width: 100%;
  font-size: 17px;
  border-radius: 6px;
  padding: 12px 0;
  font-weight: 500;
  letter-spacing: 2px;
}
.form-links {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -10px;
}
@media (max-width: 900px) {
  .login-main {
    width: 100vw;
    min-width: 0;
    border-radius: 0;
    box-shadow: none;
  }
  .login-side {
    display: none;
  }
  .login-form-card {
    margin: 0 auto;
    min-width: 0;
    max-width: 100vw;
    border-radius: 0;
    box-shadow: none;
  }
}
</style> 